package com.pssmobile.genericglossary.visual;

import java.util.Enumeration;

import javax.microedition.io.file.FileSystemRegistry;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.XYRect;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.decor.Background;
import net.rim.device.api.ui.decor.BackgroundFactory;

import com.pssmobile.genericglossary.common.TermsNavigator;
import com.pssmobile.genericglossary.data.DataAdapter;

/**
 * A class extending the MainScreen class, which provides default standard
 * behavior for BlackBerry GUI applications.
 */
public class MainForm extends MainScreen implements FieldChangeListener
{
    static Bitmap getBgBitmap() {
        Bitmap bmp;
        if (Display.getWidth() > 360) {
            bmp = Bitmap.getBitmapResource("res/bg2.jpg");
        } else {
            bmp = Bitmap.getBitmapResource("res/bg.jpg");
        }
        return bmp;
    }
    
    Bitmap _bmp;
    Background _bg;
    Background _bgTransparent;
        
    TermsListField _list;
    BasicEditField _filter;
    
    /**
     * Creates a new HelloWorldScreen object
     */
    public MainForm()
    {   
        _bmp = getBgBitmap();
        _bg = BackgroundFactory.createBitmapBackground( _bmp, Background.POSITION_X_LEFT, Background.POSITION_Y_TOP, Background.REPEAT_BOTH );;
        _bgTransparent = BackgroundFactory.createSolidTransparentBackground(0xffffff, 0);

        
        getMainManager().setBackground(_bgTransparent);
        
        // Set the displayed title of the screen       
        setTitle( new LabelField("Generic Glossary demo", FIELD_HCENTER | DrawStyle.HCENTER) );

System.out.println("Initializing db create process...");
System.out.println("The mounted roots are:");
        Enumeration roots =  FileSystemRegistry.listRoots();
        while (roots.hasMoreElements()) 
        {
           String rootName = (String)roots.nextElement();
System.out.println(rootName);
        }
        
        // Get DB data
        int termsCount = 0;
        try {
            DataAdapter.getInstance().openDatabase( "file:///SDCard/glossary/database1.db", true );
System.out.println("Status: Database was successfully opened.");            
            termsCount = TermsNavigator.getInstance().loadTerms(null);
        } catch (Exception e){
System.out.println("Error:" + e);
            add(new BasicEditField("Find: ", "Error: " + e));
            return;
        }
        
        // ListField
        _list = new TermsListField() {
            protected boolean navigationClick(int status, int time) {
                if (-1 != getSelectedIndex()) {
                    int termID = TermsNavigator.getInstance().getTermIDByIndex( getSelectedIndex() );
                    TermsNavigator.getInstance().setCurrentTerm( termID );
                    openDescription( termID );
                    return true;
                }
                return super.navigationClick(status, time);
            }
        };
        TermsNavigator.getInstance().addListener(_list);
        _list.setSize(termsCount);
        _list.setBackground(_bgTransparent);
        
        // FilterField
        _filter = new BasicEditField("Find: ", "");
        _filter.setChangeListener(this);
        _filter.setBackground(_bgTransparent);        
        
        // Add UI fields
        add(_list);        
        setStatus(_filter);
    }

    // paint custom background
    protected void paintBackground(Graphics g)
    {
        _bg.draw(g, new XYRect(0, 0, getWidth(), _bmp.getHeight()));
    }   
    
    public void openDescription( int termID) {
        DetailsForm form = new DetailsForm( termID );
        UiApplication.getUiApplication().pushScreen(form);
    }
    
    public void close()
    {
        TermsNavigator.getInstance().removeListener(_list);
        try {
            DataAdapter.getInstance().closeDatabase();
        } catch (Exception e) {}
        super.close();
    }
    
    private void handle_FilterList( String filter ) {
     // Get DB data
        int termsCount = 0;
        try {
            termsCount = TermsNavigator.getInstance().loadTerms(filter);
        } catch (Exception e){
System.out.println("Error:" + e);
        }
        _list.setSize(termsCount);
    }
    
    public void fieldChanged(Field field, int context) {
        if (_filter == field) {
            handle_FilterList(_filter.getText());
        }
    }
}
